import Cookie from 'js-cookie'
import { net } from '@/config/default'
import { setAuthorization, checkAuthorization } from '@/utils/request'
import { isArray } from '@/utils/validate'

/**
 * @description 处理code异常
 * @param {*} code
 * @param {*} msg
 */
const handleCode = (code, msg, options) => {
  const { message } = options
  switch (code) {
    case 1:
      message.error(msg || '账户或密码错误')
      break
    case 8:
      message.error(msg || '后端服务异常')
      break
    case 11:
      message.error(msg || '访问令牌失效')
      break
    case 12:
      message.error(msg || '操作无权限')
      break
    case 13:
      message.error(msg || '无效参数')
      break
    case 17:
      message.error(msg || '账户禁用或过期')
      break
    case 30:
      message.error(msg || '应用程序密钥错误')
      break
    case 400:
      message.error('请求参数异常')
      break
    case 401:
      message.error(msg || '无此权限')
      break
    case 403:
      message.error(msg || '请求拒绝')
      break
    default:
      message.error(msg || `后端接口${code}异常`)
      break
  }
}

const reqCommon = {
  /**
   * 发送请求之前
   * @param config axios config
   * @param options 应用配置 包含: {router,store, message}
   * @returns {*}
   */
  onFulfilled(config, options) {
    const { store, router } = options
    const { url, xsrfCookieName, xsrfHeaderName } = config
    const { debounce, noPermissionFilter } = net

    if (
      url.indexOf('Login') === -1 &&
      xsrfCookieName &&
      !Cookie.get(xsrfCookieName)
    ) {
      // message.warning('认证 token 已过期，请重新登录')
      router.push('/login')
    }
    //根据配置控制loading显示
    if (debounce.some((item) => url.includes(item))) {
      store.state.setting.loading = true
    }
    if (noPermissionFilter.some((item) => url.includes(item))) {
      delete config.headers[xsrfHeaderName]
    }
    return config
  },
  /**
   * 请求出错执行
   * @param error 错误对象
   * @param options 应用配置 包含: {router, store, message}
   * @returns {Promise<never>}
   */
  onRejected(error, options) {
    const { message, store } = options
    store.state.setting.loading = false
    message.error(error.message)
    return Promise.reject(error)
  },
}

const respCommon = {
  /**
   * 响应数据之前
   * @param response 响应对象
   * @param options 应用配置 包含: {router, store, message}
   * @returns {*}
   */
  onFulfilled(response, options) {
    const { store } = options
    // store.state.setting.loading = false
    setTimeout(() => {
      store.state.setting.loading = false
    }, 200)

    console.log(response, 'response')
    const { successCode, xsrfCookieName } = net
    const { data, config } = response
    const { code, msg } = data.errCode || data

    // 操作正常Code数组
    const codeVerificationArray = isArray(successCode)
      ? [...successCode]
      : [...[successCode]]
    // 是否操作正常
    if (codeVerificationArray.includes(code)) {
      //设置用户无请求操作后半个小时token 缓存清除
      if (checkAuthorization()) {
        setAuthorization({
          token: Cookie.get(xsrfCookieName),
          expireAt: new Date(new Date().getTime() + 30 * 60 * 1000),
        })
      }
      return data
    } else {
      handleCode(code, msg, options)
      return Promise.reject(
        'iot-web 响应异常拦截:' +
          JSON.stringify({ url: config.url, code, msg }) || 'Error'
      )
    }
  },
  /**
   * 响应出错时执行
   * @param error 错误对象
   * @param options 应用配置 包含: {router, store, message}
   * @returns {Promise<never>}
   */
  onRejected(error, options) {
    const { message, store } = options
    const { response, message: msg } = error
    console.log(response, 'response')

    store.state.setting.loading = false

    if (response && response.data) {
      const { status, data } = response
      console.log('response', response)
      handleCode(
        status,
        data.msg || (data.errCode && data.errCode.errMessage) || msg,
        options
      )
      return Promise.reject(error)
    } else {
      let { message: msg } = error
      if (msg === 'Network Error') {
        msg = '后端接口连接异常'
      }
      if (msg.includes('timeout')) {
        msg = '后端接口请求超时'
      }
      if (msg.includes('Request failed with status code')) {
        const code = msg.substr(msg.length - 3)
        msg = '后端接口' + code + '异常'
      }
      message.error(msg || `后端接口未知异常`)
      return Promise.reject(error)
    }
  },
}

export default {
  request: [reqCommon], // 请求拦截
  response: [respCommon], // 响应拦截
}
